/*
 * Copyright (c) 2012-2015 The original author or authors
 * ------------------------------------------------------
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Apache License v2.0 which accompanies this distribution.
 *
 * The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * The Apache License v2.0 is available at
 * http://www.opensource.org/licenses/apache2.0.php
 *
 * You may elect to redistribute this code under either of these licenses.
 */
package com.chinamobile.iot.mqtt.server.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

/**
 * Some Netty's channels utilities.
 *
 * @author andrea
 */
public class NettyUtils {

    public static final String ATTR_CLIENT_ID = "ClientId";
    public static final String ATTR_MQTT_ID = "MqttId";
    public static final String ATTR_MQTT_CLEAN_SESSION = "CleanSession";


    private static final AttributeKey<String> ATTR_KEY_CLIENT_ID = AttributeKey.valueOf(ATTR_CLIENT_ID);
    private static final AttributeKey<String> ATTR_KEY_MQTT_ID = AttributeKey.valueOf(ATTR_MQTT_ID);
    private static final AttributeKey<Boolean> ATTR_KEY_CLEAN_SESSION = AttributeKey.valueOf(ATTR_MQTT_CLEAN_SESSION);

    public static void clientId(Channel channel, String clientID) {
        channel.attr(ATTR_KEY_CLIENT_ID).set(clientID);
    }

    public static String clientId(Channel channel) {
        return channel.attr(ATTR_KEY_CLIENT_ID).get();
    }

    public static void cleanSession(Channel channel, boolean cleanSession) {
        channel.attr(ATTR_KEY_CLEAN_SESSION).set(cleanSession);
    }

    public static Boolean cleanSession(Channel channel) {
        return channel.attr(ATTR_KEY_CLEAN_SESSION).get();
    }

    public static void mqttId(Channel channel, String info) {
        channel.attr(ATTR_KEY_MQTT_ID).set(info);
    }

    public static String mqttId(Channel channel) {
        return channel.attr(ATTR_KEY_MQTT_ID).get();
    }

    public static byte[] readBytesAndRewind(ByteBuf payload) {
        byte[] payloadContent = new byte[payload.readableBytes()];
        int mark = payload.readerIndex();
        payload.readBytes(payloadContent);
        payload.readerIndex(mark);
        return payloadContent;
    }


}
